import 'dart:convert';

import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:native_dio_adapter/native_dio_adapter.dart';
import 'package:vape_xe/services/services.dart';
import 'package:vape_xe/values/server.dart';

import 'CustomInterceptor.dart';

class Request {
  static final Request _request = Request._();

  CancelToken cancelToken = CancelToken();

  late final Dio _dio;

  factory Request() => _request;

  Request._() {
    _dio = Dio();
    _dio.interceptors.add(CookieManager(CookieJar()));
    _dio.options.baseUrl = ConfigStore.to.isRelease ? baseUrl : devBaseUrl;
    _dio.httpClientAdapter = NativeAdapter();
    _dio.interceptors.add(CustomInterceptor(cancelToken));
  }

  Future post(String url, [Object? data, bool dismissDialogAuto = true]) async {
    Response response = await _dio.post(
      url,
      data: data,
      cancelToken: cancelToken,
      options: Options(extra: {'dismissDialogAuto': dismissDialogAuto}),
    );
    return jsonDecode(response.data);
  }

  Future get(String url, [Map<String, dynamic>? data, bool dismissDialogAuto = true]) async {
    Response response = await _dio.get(
      url,
      queryParameters: data,
      cancelToken: cancelToken,
      options: Options(extra: {'dismissDialogAuto': dismissDialogAuto}),
    );
    return jsonDecode(response.data);
  }
}
